import React, { useState } from 'react';
import './CreateMaterialRequest.css';

const CreateMaterialRequest = () => {
  const [requestId, setRequestId] = useState('');
  const [user, setUser] = useState('');
  const [datetime, setDatetime] = useState('');
  const [materialCounts, setMaterialCounts] = useState([
    {
      address: '',
      specifications: [
        { name: '', count: 0 },
      ],
    },
  ]);

  const addMaterialCount = () => {
    setMaterialCounts([
      ...materialCounts,
      {
        address: '',
        specifications: [
          { name: '', count: 0 },
        ],
      },
    ]);
  };

  const addSpecification = (index) => {
    const newMaterialCounts = [...materialCounts];
    newMaterialCounts[index].specifications.push({ name: '', count: 0 });
    setMaterialCounts(newMaterialCounts);
  };

  const removeSpecification = (countIndex, specIndex) => {
    const newMaterialCounts = [...materialCounts];
    newMaterialCounts[countIndex].specifications.splice(specIndex, 1);
    setMaterialCounts(newMaterialCounts);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const requestData = {
      request_id: parseInt(requestId),
      user,
      datetime,
      material_counts: materialCounts,
    };
    try {
      const response = await fetch('/create/material_request_item', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });
      const data = await response.json();
      console.log(data);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div className="page-container">
      <div className='create-material-container'>
      <div className="create-material-request">
        <h1>Create Material Request</h1>
        <form onSubmit={handleSubmit}>
          <label>
            Request ID:
            <input type="number" value={requestId} onChange={(e) => setRequestId(e.target.value)} required />
          </label>
          <br />
          <label>
            User:
            <input type="text" value={user} onChange={(e) => setUser(e.target.value)} required />
          </label>
          <br />
          <label>
            Datetime:
            <input type="datetime-local" value={datetime} onChange={(e) => setDatetime(e.target.value)} required />
          </label>
          <br />
          <h2>Material Counts</h2>
          {materialCounts.map((count, countIndex) => (
            <div key={countIndex} className="material-count">
              <h3>领取单位</h3>
              <label>
                地址:
                <input
                  type="text"
                  value={count.address}
                  onChange={(e) => {
                    const newMaterialCounts = [...materialCounts];
                    newMaterialCounts[countIndex].address = e.target.value;
                    setMaterialCounts(newMaterialCounts);
                  }}
                  required
                />
              </label>
              <br />
              <h4>物料单</h4>
              <table>
                <thead>
                  <tr>
                    <th>名称</th>
                    <th>数量</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {count.specifications.map((spec, specIndex) => (
                    <tr key={specIndex} className="material-specification">
                      <td>
                        <input
                          type="text"
                          value={spec.name}
                          onChange={(e) => {
                            const newMaterialCounts = [...materialCounts];
                            newMaterialCounts[countIndex].specifications[specIndex].name = e.target.value;
                            setMaterialCounts(newMaterialCounts);
                          }}
                          required
                        />
                      </td>
                      <td>
                        <input
                          type="number"
                          value={spec.count}
                          onChange={(e) => {
                            const newMaterialCounts = [...materialCounts];
                            newMaterialCounts[countIndex].specifications[specIndex].count = parseInt(e.target.value);
                            setMaterialCounts(newMaterialCounts);
                          }}
                          required
                        />
                      </td>
                      <td>
                        <button onClick={() => removeSpecification(countIndex, specIndex)}>Remove</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <button type="button" onClick={() => addSpecification(countIndex)}>Add Specification</button>
            </div>
          ))}
          <button type="button" className="add-button" onClick={addMaterialCount}>Add Material Count</button>
          <button type="submit">Create</button>
        </form>
      </div>
      </div>
    </div>
  );
};

export default CreateMaterialRequest;
